<?php

require_once '../../controller.php';
require_once '../../header.php';
//require_once '../../classes/Survey.php';
//require_once '../../classes/Question.php'; 
if(isset($_SESSION['logged_in'])) {
	 
	$instructor_id = $_SESSION['logged_in'];

}

if(isset($_REQUEST['sid'])){
$survey_id = $_REQUEST['sid'];
}

$s = new Survey();
$survey = $s->getSurvey($survey_id);
if(!isset($_POST['select_group']) &&!isset($_POST['set_message'])) {

	
	echo '<form name = "deliver_form" method="POST">';
	print '<ul>';
	$courses = $instructor->getAllCourses();
	if($courses) {
		foreach($courses as $c) {
			print "<li>$c->title</li>";
			$groups = $c->getAllGroups();
			if($groups) {
				print '<ul>';
				foreach($groups as $g) {
					print "<li><input name='$g->id' type='checkbox'>$g->name</li>";
				}
				print '</ul>';
			}
		}
	}
	print '</ul>';
	
	echo '<input type="submit" name = "select_group" value = "Select Group"';
	echo '</form>';
}

	if(isset($_POST['select_group'])){
	//if(isset($_POST['select_group'])) {
		foreach($_POST as $key=>$value) {
			if($key != 'select_group') {
				$selected[] = new Group($key);
			}
		}
   /*die(print_r($selected));*/
	$selected = serialize($selected);	
   echo "<table>";
   echo "<form name='setmessage' method ='POST'>";
   echo "<tr><th>Email-Subject:</th><td><input name='subject' type='text' value='".$survey['email_subject']."' size='50px'></td></tr>";
   echo "<tr><td>&nbsp;</td></tr>";
   echo "<tr><th>Email-Message:</th><td><textarea name='message' cols='50' rows='10'>".$survey['email_message']."</textarea></td></tr>";
   echo "<tr><td>&nbsp;</td></tr>";
   echo "<tr><td><input name='selected_groups' type='hidden' value='$selected'></td></tr>";
   echo "<tr><td><input type='submit' name='set_message' Value='Deliver Survey'></td></tr>";
   echo "</form>";
   echo "</table>";
	//}	
}
		
	if(isset($_POST['set_message'])){
		$subject = $_POST['subject'];
		$message = $_POST['message'];
	    $selected_groups = $_POST['selected_groups'];
	    
	    $selected_groups = unserialize($selected_groups);
	    die(print_r($selected_groups));
	    $sql = "UPDATE `survey` SET `email_subject`= '{$_POST['subject']}', `email_message`='{$_POST['message']}'
	        WHERE `id`='$survey_id'";
	    $result = mysql_query($sql) or die("Update email message:".mysql_error());
	    
		if($selected_groups) {
				foreach($selected_groups as $stu) {
				$all_students = $stu->getAllStudents();
				if($all_students) {
					foreach($all_students as $student) {
						$email_message = $message."http://".HOST."/survey/renderSurvey/publicsurvey.php?sid=".$survey_id."&mid=".$student->id;
						mail($student->email,$subject,$email_message,$headers);
					}
				}
			}
			
			echo'<h1>Survey has been delivered sucessfully</h1>';
			echo '<a href="interface.php"><font color="blue">Go Back to My Surveys</font></a>';
		}
	}	
	


require_once '../../footer.php';
	?>